package com.zzyl.job;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import com.zzyl.constant.CacheConstants;
import com.zzyl.entity.AlertRule;
import com.zzyl.mapper.AlertRuleMapper;
import com.zzyl.service.AlertRuleService;
import com.zzyl.vo.DeviceDataVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class AlertJob {
    @Autowired
    private AlertRuleService alertRuleService;
    @Autowired
    private AlertRuleMapper alertRuleMapper;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Scheduled(cron = "0 * * * * ?")
    public void deviceDataAlertFilter() {
        //查询所有报警规则,如果为空,程序结束
        List<AlertRule> allAlertRule = alertRuleMapper.selectByFunctionId(null, null, null);
        if (CollUtil.isEmpty(allAlertRule)) {
            return;
        }
        //2.查询所以设备最新的上报数据,如果为空,程序结束
        List<Object> values = redisTemplate.opsForHash().values(CacheConstants.IOT_DEVICE_LAST_DATA_KEY);
        if (CollUtil.isEmpty(values)) {
            return;
        }
        //3.设备上报不为空提取设备上报数据为list
        List<DeviceDataVo> deviceDataVos = new ArrayList<>();
        values.forEach(json -> {
            deviceDataVos.addAll(JSONUtil.toList(json.toString(), DeviceDataVo.class));
        });
        //4.对每一条设备上报数据进行报警规则校验
        deviceDataVos.forEach(deviceDataVo -> {
            alertRuleService.alertFilter(deviceDataVo);
        });
    }
}
